<?php
/**
 * Created by PhpStorm.
 * Script Name: Bot.php
 * Create: 2023/2/14 10:34
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\crontab\controller;

use plugin\wechat\app\service\Mp as MpService;
use app\PluginController;
use plugin\wechat\app\model\MpTask;
use plugin\wechat\app\service\MpFollow as FollowService;
use plugin\wechat\app\service\MpTask as TaskService;

class Mp extends PluginController
{
    /**
     * @var MpTask
     */
    private MpTask $taskM;

    public function __construct()
    {
        parent::__construct();
        $this->taskM = new MpTask();
    }

    /**
     * 拉群粉丝 (10秒执行一次)
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function pullFollow(){
        $task_list = $this->taskM->where('status', TaskService::STATUS_RUNNING)
            ->where('module', TaskService::MODULE_PULL_FOLLOW)
            ->page(1, 10)
            ->select();
        foreach ($task_list as $task){
            try {
                if($last_follow = FollowService::getLastFollow($task['mp_id'], $task['company_id'])){
                    $next_openid = $last_follow['openid'];
                }else{
                    $next_openid = '';
                }
                $mp_info = MpService::getInfo($task['mp_id']);
                if(is_string($res = FollowService::userList($next_openid, $mp_info))){
                    continue;
                }

                if(!empty($res['next_openid'])){
                    $openid_list = $res['data']['openid'];
                    if(is_string($res = FollowService::userInfoList($openid_list, $mp_info))){
                        continue;
                    }
                    $follow_list = $res['user_info_list'];
                    foreach ($follow_list as $item) {
                        $item['company_id'] = $task['company_id'];
                        $item['mp_id'] = $task['mp_id'];
                        $res = FollowService::insertOne($item);
                        //var_dump($res);
                    }
                }else{
                    //说明到底了
                    $this->taskM->update(['id' => $task['id'], 'status' => TaskService::STATUS_FINISH]);
                    continue;
                }
            }catch (\Exception $e){
                //异常的公众号自动完成任务
                $this->taskM->update(['id' => $task['id'], 'status' => TaskService::STATUS_FINISH]);
                dao_log()->error("拉取粉丝异常：");
                dao_log()->error($e->getMessage());
                var_dump("拉取粉丝异常：");
                var_dump($e->getMessage());
            }
        }
    }
}